import { trendRank } from '@/services/api/api-analysis';
import { DrawerForm, PageContainer } from '@ant-design/pro-components';
import { useAccess, useLocation, useModel } from '@umijs/max';
import { Avatar, Cascader, Col, DatePicker, Empty, Flex, Progress, Row } from 'antd';
import Paragraph from 'antd/lib/typography/Paragraph';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import styles from '../browser/components/RankTabsModule2/components/TrendCuesRankCardStyle.less';
import PreviewModule from './PreviewModule';
export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const access = useAccess();

  const { currentUser } = initialState || {};
  let location = useLocation();
  //排行榜筛选项
  const organizationTopIdOptions = [
    {
      value: '',
      label: '全部',
    },
    {
      value: '6000000000100000',
      label: '市委宣传部',
    },
    {
      value: '6000000000200000',
      label: '中央媒体',
    },
    {
      value: '6000000000300000',
      label: '市属媒体',
    },
    {
      value: '6000000000400000',
      label: '市外媒体',
    },

    {
      value: '6000000000700000',
      label: '市级部门',
    },
    {
      value: '6000000000900000',
      label: '区县',
    },
    //没有排行
    {
      value: '6000000001400000',
      label: '社会团体',
    },
    {
      value: '6000000001700000',
      label: '高等院校',
    },
    {
      value: '6000000001600000',
      label: '央企或在渝大型企业',
    },
    {
      value: '6000000002100000',
      label: '国有企业',
    },
  ];

  const dataTabTypeOptions = [
    {
      value: '1',
      label: '选题计划',
    },
    {
      value: '2',
      label: '报送选题',
    },
    {
      value: '3',
      label: '主动报送',
    },
  ];
  const monthFormat = 'YYYY-MM';

  const rankIcon = [
    '/image/排行榜第一名（56X56）.png',
    '/image/排行榜第二名（56X56）.png',
    '/image/排行榜第三名（56X56）.png',
  ];

  const startDate = moment().startOf('month');
  const endOfDate = moment();
  const [loading, setLoadingState] = useState<boolean>(true);
  const [dataTrendCuesRank, setDataTrendCuesRankState] = useState<AnalysisData.TrendRank[]>([]);
  const [dataTrendCuesRankList, setDataTrendCuesRankListState] = useState<AnalysisData.TrendRank[]>(
    [],
  );
  //线索报送量、线索收录量
  const [dataTabType, setDataTabState] = useState<string>(dataTabTypeOptions[0].value);
  const [dataTabTypeName, setDataTabNameState] = useState<string>(dataTabTypeOptions[0].label);
  //日期范围
  const [dataDates, setDataDatesState] = useState<string[]>([
    startDate.format(monthFormat),
    endOfDate.format(monthFormat),
  ]);
  //选择单位类型
  const [dataOrganizationTopName, setDataOrganizationTopNameState] = useState<string>(
    organizationTopIdOptions[0].label,
  );
  const [dataOrganizationTopId, setDataOrganizationTopIdState] = useState<string>(
    organizationTopIdOptions[0].value,
  );
  //排行榜列表
  const renderRank = (item: AnalysisData.TrendRank, index: number) => {
    let max = 1;
    if (dataTrendCuesRank.length > 0) {
      max = dataTrendCuesRank[0].count + dataTrendCuesRank[0].count / 10;
    }

    return (
      <>
        <Row
          style={{
            alignItems: 'center',
            height: '48px',
            // marginTop:"5px",
          }}
        >
          <Col span={3}>
            <div style={{ width: '30px' }}>
              {index <= 2 ? (
                <Avatar size={38} src={rankIcon[index]}></Avatar>
              ) : (
                <div
                  style={{
                    backgroundColor: '#5083E1',
                    borderRadius: '50%',
                    width: '25px',
                    height: '25px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginLeft: '8px',
                    color: 'white',
                  }}
                >
                  {index + 1}
                </div>
              )}
            </div>
          </Col>
          <Col span={7}>
            <Paragraph
              ellipsis={true}
              style={{ marginTop: '13px', fontSize: '11px', fontWeight: 'bold' }}
            >
              {item?.organizationName}
            </Paragraph>
          </Col>
          <Col span={14} style={{ marginTop: '5px' }}>
            <Progress
              percent={Math.round((item.count / max) * 100)}
              format={(percent) => (
                <span style={{ fontSize: '11px', fontWeight: 'bold' }}>{item.count}篇</span>
              )}
              // style={{ marginLeft: '5%' }}
              strokeWidth={11}
            />
          </Col>
          {/* <Col span={4}>col-8</Col> */}
        </Row>
      </>
    );
  };

  /**
   * 线索征集
   * @param key
   */
  const loadTrendCuesRankData = async (
    dataDates: string[],
    organizationTopId: string,
    dataTabType: string,
  ) => {
    try {
      const response = await trendRank({
        type: dataTabType,
        organizationTopId: organizationTopId,
        startTime: dataDates[0],
        endTime: dataDates[1],
      });
      if (response.code === 0) {
        setDataTrendCuesRankState(response.data);
        setDataTrendCuesRankListState(response.data.slice(0, 10));
        console.log(access);

        setLoadingState(false);
      }
    } catch (error) {}
  };

  useEffect(() => {
    loadTrendCuesRankData(dataDates, dataOrganizationTopId, dataTabType);
  }, []);
  const topColResponsiveProps = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 12,
    xl: 6,
    style: { marginBottom: 24, padding: window.innerWidth < 400 ? '0px' : '12px' },
  };

  return (
    <>
      {loading ? (
        <></>
      ) : (
        <>
          <PageContainer
            header={{
              breadcrumb: {},
              title: false,
            }}
          >
            <PreviewModule />
            <Flex justify={'space-between'} align={'center'} style={{ marginBottom: 10 }}>
              {/* <span>排行榜</span> */}

              <Cascader
                defaultValue={[dataTabType]}
                options={dataTabTypeOptions}
                onChange={(value: any[], selectOptions: any) => {
                  setDataTabState(value[value.length - 1]);
                  setDataTabNameState(
                    selectOptions.map((item: { label: any }) => item.label).join(' > '),
                  );
                  loadTrendCuesRankData(dataDates, dataOrganizationTopId, value[value.length - 1]);
                }}
                //style={{borderBottom:'2px solid #1677FF'}}
              >
                <a>{dataTabTypeName}</a>
              </Cascader>
              {access.线索征集x配置x管理员 ? (
                <Cascader
                  defaultValue={[dataOrganizationTopId]}
                  options={organizationTopIdOptions}
                  onChange={(value: any[], selectOptions: any) => {
                    setDataOrganizationTopIdState(value[value.length - 1]);
                    setDataOrganizationTopNameState(
                      selectOptions.map((item: { label: any }) => item.label).join(' > '),
                    );
                    loadTrendCuesRankData(dataDates, value[value.length - 1], dataTabType);
                  }}
                >
                  <a>{dataOrganizationTopName}</a>
                </Cascader>
              ) : (
                <></>
              )}
              <DatePicker
                popupStyle={{ width: 300 }}
                style={{ width: 100 }}
                allowClear={false}
                inputReadOnly={false}
                defaultValue={dayjs()}
                format={monthFormat}
                picker="month"
                onChange={(values, dates) => {
                  setDataDatesState([dates, dates]);
                  loadTrendCuesRankData([dates, dates], dataOrganizationTopId, dataTabType);
                }}
              />
            </Flex>

            <Row gutter={24}>
              <Col {...topColResponsiveProps}>
                {dataTrendCuesRank.length > 0 ? (
                  <div
                    style={{
                      borderStyle: 'solid',
                      border: '1px solid #f0f0f0',
                      borderRadius: 8,
                      padding: 20,
                    }}
                  >
                    <Flex justify={'flex-end'} align={'flex-end'} style={{ marginRight: 8 }}>
                      <DrawerForm
                        title={'排行榜'}
                        trigger={
                          <a
                            hidden={!(dataTrendCuesRank && dataTrendCuesRank?.length > 0)}
                            style={{ fontWeight: 'bold' }}
                          >
                            详情
                          </a>
                        }
                        submitter={false}
                        width={400}
                      >
                        <ul
                          className={styles.rankingList}
                          style={{
                            margin: '-25px 0 0',
                          }}
                        >
                          {dataTrendCuesRank && dataTrendCuesRank?.length > 0 ? (
                            dataTrendCuesRank?.map((item, i) => (
                              <li key={item.organizationId}>
                                <span
                                  className={`${styles.rankingItemNumber} ${
                                    i < 3 ? styles.active : ''
                                  }`}
                                >
                                  {i + 1}
                                </span>
                                <span
                                  className={styles.rankingItemTitle}
                                  title={item.organizationName}
                                >
                                  {item.organizationName}
                                </span>
                                <span>{item.count}篇</span>
                              </li>
                            ))
                          ) : (
                            <Empty />
                          )}
                        </ul>
                      </DrawerForm>
                    </Flex>
                    {dataTrendCuesRankList.map((item, index) => renderRank(item, index))}
                  </div>
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
              </Col>
            </Row>
          </PageContainer>
        </>
      )}
    </>
  );
};
